package com.me.study.concurrent.threadPool;

import com.me.common.util.io.HttpUtils;
import org.apache.http.util.EntityUtils;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 设定一个并发度，一起执行。用来压测、性能测试、并发测试
 */
public class CountDownLatchUtil {

    private CountDownLatch count, down;
    private int pollSize = 500;

    public CountDownLatchUtil() {
        this(10);
    }

    public CountDownLatchUtil(int pollSize) {
        this.pollSize = pollSize;
        count = new CountDownLatch(pollSize);
        down = new CountDownLatch(pollSize);
    }

    public void latch(Runnable runnable) throws InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(pollSize);
        for (int i = 0; i < pollSize; i++) {
            final int i1 = i;
            executorService.submit(() -> {
                try {
                    count.countDown();
                    count.await();
                    System.out.println("开始执行" + i1 + ": \t\t" + new Date().toLocaleString());
                    long start = System.currentTimeMillis();
                    runnable.run();
                    System.out.println("任务" + i1 + "耗时：\t\t" + (System.currentTimeMillis() - start));
                } catch (Exception e) {
                    // e.printStackTrace();
                    System.out.println("任务" + i1 + "异常：\t\t" + e.getMessage());
                } finally {
                    down.countDown();
                }
            });
        }

        Thread.sleep(500);
        down.await();
        System.out.println("结束执行");
        executorService.shutdown();
    }

}

